<template>
    <div class="mod-prod-prodTag">
        <avue-crud ref="crud" :data="dataList" :option="tableOption" :page="page" :table-loading="dataListLoading" :search="query"
                   @selection-change="selectionChange" @search-change="searchChange" @refresh-change="">
            <template slot="menuLeft">
                <el-button icon="el-icon-plus" size="small" type="primary"
                           @click="addOrUpdateHandle()">开始自评
                </el-button>
<!--                <el-button :disabled="dataListSelections.length <= 0" icon="el-icon-error" size="small" type="success"-->
<!--                           @click="handleConfirm">提交审核-->
<!--                </el-button>-->
                <!-- <el-button type="danger" size="small" icon="el-icon-error" :disabled="dataListSelections.length <= 0"
							@click="">作废重评</el-button> -->
            </template>

            <template slot="status" slot-scope="scope">
                <el-tag v-if="scope.row.status === 0" size="small" type="danger">禁用</el-tag>
                <el-tag v-else size="small">正常</el-tag>
            </template>

            <template slot="isDfault" slot-scope="scope">
                <el-tag v-if="scope.row.isDefault === 0" size="small">自定义类型</el-tag>
                <el-tag v-else size="small">默认类型</el-tag>
            </template>

            <template slot="menu" slot-scope="scope">
                <el-button icon="el-icon-edit" size="small" type="primary"
                           @click="editFilling(scope.row)">修改
                </el-button>
                <el-button icon="el-icon-upload" size="small" type="warning"
                           @click.stop="handleConfirm(scope.row)">提交审核
                </el-button>
                <el-button icon="el-icon-delete" size="small" type="danger"
                           @click.stop="delFilling(scope.row)">作废重评
                </el-button>
            </template>

        </avue-crud>
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @initFail="initFail"
                       @initSuccess="initSuccess"></add-or-update>
        <el-dialog title="数据填报详情" :close-on-click-modal="false" :visible.sync="editVisible" width="95%" height="90vh" top="5vh" custom-class="my-dialog">
            <target-edit ref="editRef" :editFormData="editFormData" controlType="area" @success="success"></target-edit>
        </el-dialog>
    </div>
</template>

<script>
import {
	tableOption
} from '@/crud/filling/filling'
import AddOrUpdate from './main-add-or-update.vue'
import {statusList} from '@/utils/data'
import TargetEdit from '@/template/target-edit/index.vue'

export default {
	data () {
		return {
            params: {
                reginId: "",
                evalYear: wfy.format('yyyy', new Date()),
                evalStatus: "",
            },
			editFormData: {},
            editVisible: false,
			dataList: [],
			yearsList: [],
			page: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10 // 每页显示多少条
			},
            query: {
                evalYear: wfy.format('yyyy', new Date())
            },
			dataListSelections: [],
			dataListLoading: false,
			tableOption: tableOption,
			permission: {
				delBtn: this.isAuth('prod:prodTag:delete')
			},
			addOrUpdateVisible: false
		}
	},
	components: {
		TargetEdit,
		AddOrUpdate
	},
	created () {
	},
	activated () {
		if (!wfy.empty(wfy.getPara('reginId'))) {
			this.getDataList(1, {
				reginId: wfy.getPara('reginId'),
				evalYear: wfy.getPara('evalYear'),
				evalStatus: wfy.getPara('evalStatus'),
			})
		}else{
            this.getDataList(1, this.params);
        }
	},
	mounted () {
		this.init()
	},
	methods: {
		init () {
			this.yearsList = []
			for (let i = 2024; i < 2060; i++) {
				this.yearsList.push({
					value: i,
					label: i
				})
			}
			let areaList = this.$store.state.user.area.area
			this.tableOption.column.forEach((item) => {
				if (item.prop === 'evalYear') {
					item.dicData = this.yearsList
				}
				if (item.prop === 'evalStatus') {
					item.dicData = statusList
				}
				if (item.prop === 'reginId') {
					areaList.forEach((area) => {
						item.dicData.push({
							value: area.code,
							label: area.name
						})
					})
					console.log('🚀 ~ item.dicData', item.dicData)
				}
			})
            // this.getDataList(1, {
            //     reginId: "",
            //     evalYear: wfy.format('yyyy', new Date()),
            //     evalStatus: "",
            // })
		},
		getDataList (page, params, done) {
			this.dataListLoading = true
			this.dataList = []
            this.params = params;
			this.$http({
				url: this.$http.adornUrl('/eval/getEvalInfoList'),
				method: 'post',
				data: this.$http.adornData(
					Object.assign(
						{
							current: page == null ? this.page.currentPage : page.currentPage,
							size: page == null ? this.page.pageSize : page.pageSize
						},
						params
					)
				)
			}).then(({
				data
			}) => {
				console.log('🚀 ~ data', data)
				this.dataList = data
				// this.totalResult.forEach((item) => {
				//     this.dataList.push(item.evaluationMain)
				// })
				this.page.total = data.length
				this.dataListLoading = false
				if (done) {
					done()
				}
			})
		},
		// 新增 / 修改
		addOrUpdateHandle (id) {
			this.addOrUpdateVisible = true
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init(id)
			})
		},
		// 修改
		editFilling (row) {
			console.log('🚀 ~ row', row)
			if (row.evalStatus === 'O' || row.evalStatus === 'N') {
				this.$http({
					url: this.$http.adornUrl('/eval/getNowEvalInfo'),
					method: 'post',
					data: this.$http.adornData({
						'evalMainId': row.evalMainId,
						'evalYear': row.evalYear,
						'reginId': row.reginId
					})
				}).then(({
					data
				}) => {
					console.log('🚀 ~ data', data)
					let orReadyItem = {
						affixList: data[0].affixList,
						anIndexEvaluationMain: data[0].evaluationMain,
						currentEvalDtl: data[0].currentEvalDtl,
						currentIndexInfo: data[0].currentIndexInfo,
						scoreList: data[0].scoreList
					}
					this.initSuccess(orReadyItem)
				})
			} else {
				this.$alert('当前状态不可修改', '友情提醒')
			}
		},
		delFilling (row) {
			console.log('🚀 ~ row', row)
			if (row.evalStatus === 'O' || row.evalStatus === 'N') {
				this.$http({
					url: this.$http.adornUrl('/eval/delNowEvalInfo'),
					method: 'post',
					data: this.$http.adornData({
						'evalMainId': row.evalMainId,
						'evalYear': row.evalYear,
						'reginId': row.reginId
					})
				}).then(({
					data
				}) => {
					this.$message({
						message: '操作成功',
						type: 'success',
						duration: 1500,
						onClose: () => {
							this.getDataList(this.page)
						}
					})
				})
			} else {
				this.$alert('当前状态不可删除和作废', '友情提醒')
			}
		},
		handleConfirm (row) {
      if (row.evalStatus === 'O' || row.evalStatus === 'N') {
        this.auditFunction([row])
      }else {
        this.$alert('当前状态不可再提交', '友情提醒')
      }
		},
		auditFunction (checkedArr) {
			let promiseArr = []
			checkedArr.forEach((item) => {
				promiseArr.push(this.updMainSelCol(item))
			})
			Promise.all(promiseArr).then(allRes => {
				this.$message({
					message: '操作成功',
					type: 'success',
					duration: 1500,
					onClose: () => {
						this.getDataList(this.page)
					}
				})
			})
		},
		// 主信息操作
		updMainSelCol (evalMain) {
			return new Promise((resolve) => {
				this.$http({
					url: this.$http.adornUrl('/eval/updMainSelCol'),
					method: 'post',
					data: this.$http.adornData({
						'evalMainId': evalMain.evalMainId,
						'evalStatus': 'C'
					})
				}).then(({
					data
				}) => {
                    if(data === "OK"){
                        resolve(true)
                    }else{
                        this.$alert(data,"友情提醒");
                    }
				})
			})
		},
		// 多选变化
		selectionChange (val) {
			this.dataListSelections = val
		},
		// 获取选中的商品Id列表
		getSeleProdIds () {
			return this.dataListSelections.map(item => {
				return item.indexId
			})
		},
		/**
		 * 刷新回调
		 */
		refreshChange () {
			this.getDataList(this.page)
		},
		initSuccess (data) {
			console.log('🚀 ~ data', data)
			// sessionStorage.areaInitFormData = JSON.stringify(wfy.deepCopy(data))
			// this.$router.push({
			// 	path: 'filling-reporting',
			// 	query: {id: data.anIndexEvaluationMain.evalMainId}
			// })


            this.editFormData = data;
            this.$nextTick(() => {
                this.editVisible = true;
                this.$refs.editRef.initData();
            })

		},
		// 新增失败  -- 一般是指标没有对应
		initFail () {

		},
		searchChange (params, done) {
			console.log('🚀 ~ params', params)
			if (wfy.empty(params)) {
				this.$message.warning('查询条件不能为空')
				done()
				return
			}
			/*****
            if(wfy.empty(params.reginId)){
                this.$message.warning('填报区县不能为空');
                done()
                return;
            }
            if(wfy.empty(params.evalYear)){
                this.$message.warning('填报年度不能为空');
                done()
                return;
            }
            if(wfy.empty(params.evalStatus)){
                this.$message.warning('请选择状态');
                done()
                return;
            }*/
			this.getDataList(this.page, params, done)
		},
		success (message) {
            this.editVisible = false;
			this.$alert('您已填报完成，请等待审核结果！', '友情提醒', {
				callback: () => {
                    this.getDataList(1, {
                        reginId: message.reginId,
                        evalYear: message.evalYear,
                        evalStatus: message.evalStatus,
                    })
				}
			})
		}
	}
}
</script>

<style scoped>

.mod-prod-prodTag >>> .my-dialog{
    height: 90vh !important;
    overflow-y: scroll;
}

</style>
